package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    //查询所有
    @Override
    public List<Address> findAll() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(wrapper);
    }

    //新增地址
    @Override
    public void save(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);
        addressMapper.insert(address);
    }

    @Override
    public void setDefault(Long id) {
        //1.先把数据库中所有地址都设置非默认地址0
        //update address_bool set is_default = 0 where userid=#{id}
        //设置更新条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        //设置更新内容
        Address address = new Address();
        address.setIsDefault(0);
        //执行更新
        addressMapper.update(address, wrapper);
        //2.将前端传递过来的地址设置为默认地址
        address.setId(id);
        address.setIsDefault(1);
        addressMapper.updateById(address);

    }

    @Override
    public Address findDefault() {
        //select * from address_bool where userid=#{id} and is_default=1
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId())
                .eq(Address::getIsDefault, 1);
        return addressMapper.selectOne(wrapper);
    }

    @Override
    public Address findById(Long id) {
        return addressMapper.selectById(id);

    }

    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void deleteById(Long ids) {
        addressMapper.deleteById(ids);
    }
}
